const orderModel = require('../model/order');
const houseTypeModel = require('../model/houseType');
const houseTypeRecordModel = require('../model/houseTypeRecord');
const customerModel = require('../model/customeUser');
const moment = require('moment');
const mongoose = require('mongoose');
const otherConsumerModel = require('../model/otherConsumeRecord');
const xlsx = require('node-xlsx');
const fs = require('fs');
const path = require('path');

function resolvePath (name) {
    return path.resolve(__dirname, '../public' + '/name')
}

function fsPromise(path,buffer){
    return new Promise((resolve, reject) => {
        fs.writeFile(path, buffer, (err) => {
            if(err){
                reject(err)
                return
            } else {
                resolve();
            }
        })
    })
}

function formatDate(time) {
    return new Date(moment(time).format("YYYY-MM-DD")).toLocaleString()
}

function cellItem (data) {
    return data?data:null;
}

function getReduceDay (start, end) {
    let startDate = new Date(start);
    let endDate = new Date(end);
    console.log(start);
    return (endDate.getTime() - startDate.getTime()) / (1000*60*60*24)
}

function getComputedAmount (reduceDay, price, cashPledge) {
    return reduceDay * price + cashPledge
}

function getUsersObjectId (arr) {
    return arr.map(item => mongoose.Types.ObjectId(item))
}

function getArrObjectId (arr) {
    return arr.map(item => mongoose.Types.ObjectId(item))
}

async function addOrder (req, res, next) {
    try {
        let {
            houseType,
            startTime,
            endTime,
            houseNum,
            houseData, // 房间编号
            payType, // 1. 现金支付 2. 支付宝支付 3. 微信支付 4. 银联支付
            transitionAmount, // 实付金额
            users // 用户
        } = req.body;

        let houseTypeItem = await houseTypeModel.findById(houseType);
        let houseItem = await houseTypeRecordModel.findById(houseTypeItem.record);

        console.log(houseItem._id);

        if(houseItem){
            let startDate = formatDate(startTime);
            let endDate = formatDate(endTime);
            let reduceDate = getReduceDay(startDate,endDate);
            console.log(reduceDate, 'reduceDate');
            let computedAmount = getComputedAmount(reduceDate, houseItem.price,  houseItem.cashPledge);
            // 应付金额
            if(transitionAmount != computedAmount){
                res.json({
                    code: 400,
                    msg: '非法请求，计算金额与服务器不符'
                })
            } else {
                const data = await orderModel.create({
                    houseType:houseItem._id,
                    houseNum,
                    startTime: startDate,
                    endTime: endDate,
                    houseData, // 房间编号
                    payType, // 1. 现金支付 2. 支付宝支付 3. 微信支付 4. 银联支付
                    transitionAmount, // 实付金额
                    computedAmount, // 最终确认金额
                })
                let usersData = [];
                for(let i = 0; i < users.length; i++) {
                    let item = users[i];
                    const user = await customerModel.create({
                        name: item.name,
                        phone: item.phone,
                        order: data._id,
                        idCard: item.idCard
                    })
                    usersData.push(user._id)
                }
                console.log(usersData, 'usersData');
                await data.set({
                    users: usersData
                });
                await data.save();

                res.json({
                    code: 200,
                    msg: '添加订单成功！'
                })
            }
        } else {
            res.json({
                code: 400,
                msg: '没有该房型'
            })
        }

    } catch(err) {
        next(err)
    }
}

async function leaveHotel (req, res, next) {
    try {
        let {
            orderId,
            leaveTime,
            other,
            otherRemark,
            // others,
            // othersNum,
            transitionAmount // 实付金额
        } = req.body;

        const orderItem = await orderModel
            .findById(orderId)
            .populate('houseType')

        if(orderItem){
            // let othersArr = [];
            let startDate = formatDate(orderItem.startTime);
            let leaveDate = formatDate(leaveTime);
            console.log(startDate, '开始时间');
            console.log(leaveDate, '结束时间');
            let reduceDay = getReduceDay(startDate, leaveDate);
            console.log(reduceDay, '相差天数');
            let computedAmount = getComputedAmount(reduceDay, orderItem.houseType.price, orderItem.houseType.cashPledge);
            // let computedOthers = 0;

            // for(let i = 0; i < others.length; i++) {
            //     let item = others[i];
            //     const data = await otherConsumerModel.findById(item);
            //     othersArr.push(data)
            // }
            // let othersItems = othersArr.map((item, index) => {
            //     return {
            //         item,
            //         num: othersNum[index]
            //     }
            // })
            // othersItems.map(item => {
            //     computedOthers += (item.item.payMoney*item.num);
            // })
            // computedOthers += Number(other);
            console.log(other, '其他消费');
            console.log(Number(orderItem.houseType.cashPledge), '押金');
            computedAmount += Number(other);
            computedAmount -= Number(orderItem.houseType.cashPledge);
            console.log(computedAmount, '实际金额');

            console.log(transitionAmount, 'qianduan');
            if(computedAmount != transitionAmount) {
                res.json({
                    code: 400,
                    msg: '非法订单, 实付金额非法'
                })
            } else {
                await orderItem.set({
                    computedAmount,
                    transitionAmount,
                    leaveTime,
                    other,
                    otherRemark,
                    orderType: 2
                })
                await orderItem.save();
                res.json({
                    code: 200,
                    msg: '离店成功！'
                })
            }
        } else {
            res.json({
                code: 400,
                msg: '没有该订单'
            })
        }

    } catch(err) {
        next(err)
    }
}

async function getOrder (req, res, next) {
    try {
        let {pn = 1, size = 10, orderType} = req.query;
        let queryObj = {};
        if (orderType) {
            queryObj = {
                orderType: Number(orderType)
            }
        } else {
            queryObj = {

            }
        }
        console.log(queryObj);

        const orderData = await orderModel
            .find(queryObj)
            .sort({_id: -1})
            .limit(size)
            .skip((pn - 1) * size)
            .populate('houseType')
            .populate('users')

        res.json({
            code: 200,
            data: orderData
        })
    } catch(err) {
        next(err)
    }
}

async function getOrderByQuery (req, res, next) {
    try {
        let {phone,name} = req.query;
        let queryJson;
        if(phone&&name){
            queryJson = {
                phone,name
            }
        } else if(phone){
            queryJson = {
                phone
            }
        } else if(name) {
            queryJson = {
                name
            }
        }

        const customerData = await customerModel
            .find(queryJson)
            .sort({_id: -1})

        let orderIds = customerData.map(item => item.order)
        let orderData = [];

        for(let i = 0; i < orderIds.length; i++) {
            const orderItem = await orderModel
                .findById(orderIds[i])
                .populate('users');
            orderData.push(orderItem);
        }

        res.json({
            code: 200,
            data: orderData
        })
    } catch(err) {
        next(err)
    }
}

async function getExcel (req, res, next) {
    try {
        let orderData;
        orderData = await orderModel
            .find({orderType: 2})
            .sort({_id: -1})
            .populate('users')
            .populate('houseType')

        // console.log(orderData);
        let data = [
            ['交易记录报表'],
            ['订单编号','房间号', '姓名', '入住时间', '离店时间', '消费金额']
        ]
        orderData.map(item => {
            // console.log(item);
            let orderId = item._id
            let houseData = item.houseData;
            let userName = item.users[0].name;
            let startTime = moment(item.startTime).format('YYYY-MM-DD hh-mm-ss');
            let leaveTime = item.leaveTime ? moment(item.leaveTime).format('YYYY-MM-DD hh-mm-ss'): null;
            let payType = "现金支付";
            let endGetMoney = item.computedAmount;
            data.push(
                [
                    orderId,
                    houseData,
                    userName,
                    startTime,
                    leaveTime,
                    endGetMoney
                ]
            )
        })
        function getSum (arr, nameIndex) {
            let sum = 0;

            console.log(1111);
            arr.map((item, index, currArr) => {
                if(index < currArr.length && index > 1){
                    console.log(item, "项目");
                    sum += Number(item[nameIndex]);
                }
            })
            return sum
        }
        data.push([
            "合计: ",
            null,
            null,
            null,
            "消费金额",
            getSum(data, 5)
        ])
        let range = {s: {c: 0, r: 0}, e: {c: 5, r: 0}}
        let options = {'!merges': [range]};
        const xlsxData = xlsx.build([{name: "交易记录报表", data}], options);
        const fileName = `Excel-${Math.round(Date.now() / 1000)}.xlsx`;
        await fsPromise(resolvePath(fileName), xlsxData);
        res.download(resolvePath(fileName), fileName);

        // orderData.map(item => {
        //
        // })
        //
        // res.json({
        //     code: 200,
        //     data: orderData
        // })
    } catch(err) {
        next(err)
    }
}

module.exports = {
    addOrder,
    leaveHotel,
    getOrderByQuery,
    getOrder,
    getExcel
}
